<template>
    <div class="chat-container">
        <div class="messages-container">
            <div v-for="(message, index) in messages" :key="index" :class="['message', message.role]">
                <div class="message-content">
                    {{ message.content }}
                </div>
            </div>
            <div v-if="isLoading" class="loading-indicator">
                <div class="dot-flashing"></div>
            </div>
            <div v-if="error" class="error-message">
                {{ error }}
                <button @click="retryLastMessage">重试</button>
            </div>
        </div>

        <div class="input-container">
            <textarea v-model="userInput" @keydown.enter.exact.prevent="sendMessage" placeholder="输入你的问题..." rows="1"
                ref="textarea"></textarea>
            <button @click="sendMessage" :disabled="isLoading">
                <span v-if="!isLoading">发送</span>
                <span v-else class="sending">发送中...</span>
            </button>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'

const API_ENDPOINT = 'https://api.deepseek.com/chat/completions'
const API_KEY = 'sk-2bb0ba423b5042dcb6d6b577843ad707'

const messages = reactive([])
const userInput = ref('')
const isLoading = ref(false)
const error = ref(null)
const textarea = ref(null)

const adjustTextareaHeight = () => {
    textarea.value.style.height = 'auto'
    textarea.value.style.height = `${textarea.value.scrollHeight}px`
}

const scrollToBottom = () => {
    nextTick(() => {
        const container = document.querySelector('.messages-container')
        container.scrollTop = container.scrollHeight
    })
}

const sendMessage = async () => {
    const input = userInput.value.trim()
    if (!input || isLoading.value) return

    // 添加用户消息
    messages.push({
        role: 'user',
        content: input
    })

    // 准备AI消息
    const aiMessage = {
        role: 'assistant',
        content: ''
    }
    messages.push(aiMessage)

    userInput.value = ''
    isLoading.value = true
    error.value = null
    adjustTextareaHeight()
    scrollToBottom()

    try {
        const response = await fetch(API_ENDPOINT, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${API_KEY}`
            },
            body: JSON.stringify({
                model: "deepseek-chat",
                messages: messages.slice(0, -1).map(m => ({
                    role: m.role,
                    content: m.content
                })),
                temperature: 0.7,
                stream: true // 1. 开启流式输出
            })
        })

        // 2. 创建读取器
        const reader = response.body.getReader()
        const decoder = new TextDecoder()
        let done = false

        // 3. 流式读取数据
        while (!done) {
            const { value, done: streamDone } = await reader.read()
            done = streamDone

            if (value) {
                const chunk = decoder.decode(value)
                const lines = chunk.split('\n').filter(line => line.trim())

                for (const line of lines) {
                    try {
                        const message = line.replace(/^data: /, '')
                        if (message === '[DONE]') break

                        const parsed = JSON.parse(message)
                        const content = parsed.choices[0]?.delta?.content

                        if (content) {
                            aiMessage.content += content
                            scrollToBottom() // 实时滚动
                        }
                    } catch (e) {
                        console.error('解析错误:', e)
                    }
                }
            }
        }

        //   if (!response.ok) {
        //     throw new Error(`API请求失败: ${response.status}`)
        //   }

        //   const data = await response.json()
        //   aiMessage.content = data.choices[0].message.content
    } catch (err) {
        error.value = `请求出错: ${err.message}`
        messages.pop() // 移除正在生成的AI消息
    } finally {
        isLoading.value = false
        scrollToBottom()
    }
}

const retryLastMessage = () => {
    error.value = null
    const lastUserMessage = messages.filter(m => m.role === 'user').pop()
    if (lastUserMessage) {
        userInput.value = lastUserMessage.content
        messages.splice(messages.indexOf(lastUserMessage) + 1)
        sendMessage()
    }
}

onMounted(() => {
    // 初始化示例消息
    messages.push({
        role: 'assistant',
        content: '你好！我是DeepSeek学习助手，有什么问题就交给我吧！'
    })
})
</script>

<style scoped>
/* 容器整体样式 */
.chat-container {
    display: flex;
    flex-direction: column;
    height: 100%;
    background: #f8f9fa;
    border-radius: 12px;
    overflow: hidden;
    width: 100vw;
    /* 改为视窗宽度 */
}

/* 消息区域 */
.messages-container {
    flex: 1;
    padding: 20px;
    overflow-y: auto;
    display: flex;
    flex-direction: column;
    gap: 16px;
    background: linear-gradient(180deg, #f8f9fa 0%, #ffffff 100%);
}

/* 消息气泡通用样式 */
.message {
    max-width: 80%;
    padding: 12px 16px;
    border-radius: 18px;
    line-height: 1.5;
    font-size: 14px;
    animation: messageAppear 0.25s ease-out;
    position: relative;
    transition: transform 0.2s ease;
}

/* 用户消息 */
.message.user {
    background: #1890ff;
    color: white;
    align-self: flex-end;
    border-bottom-right-radius: 4px;
    box-shadow: 0 2px 6px rgba(24, 144, 255, 0.2);
}

/* 助手消息 */
.message.assistant {
    background: white;
    align-self: flex-start;
    border: 1px solid #e9ecef;
    border-bottom-left-radius: 4px;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
    white-space: pre-wrap;
    /* 保留换行格式 */
    word-break: break-word;
    /* 自动换行 */
}

.sending {
    opacity: 0.7;
}

/* 输入区域 */
.input-container {
    padding: 16px 20px;
    background: white;
    border-top: 1px solid #e9ecef;
    display: flex;
    gap: 12px;
    align-items: flex-end;
}

textarea {
    flex: 1;
    padding: 12px 16px;
    border: 1px solid #e9ecef;
    border-radius: 12px;
    resize: none;
    min-height: 44px;
    max-height: 120px;
    font-size: 14px;
    line-height: 1.5;
    transition: all 0.2s ease;
}

textarea:focus {
    border-color: #1890ff;
    box-shadow: 0 0 0 3px rgba(24, 144, 255, 0.1);
    outline: none;
}

button {
    padding: 8px 20px;
    background: #1890ff;
    color: white;
    border: none;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.2s ease;
    height: 44px;
}

button:hover:not(:disabled) {
    background: #1474d4;
    transform: translateY(-1px);
}

button:disabled {
    background: #adb5bd;
    cursor: not-allowed;
}

/* 加载动画 */
.loading-indicator {
    padding: 12px 16px;
    background: white;
    border-radius: 12px;
    align-self: flex-start;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}

.dot-flashing {
    position: relative;
    width: 8px;
    height: 8px;
    border-radius: 4px;
    background-color: #1890ff;
    animation: dotFlashing 1s infinite linear;
}

.dot-flashing::before,
.dot-flashing::after {
    content: '';
    position: absolute;
    width: 8px;
    height: 8px;
    border-radius: 4px;
    background-color: #1890ff;
}

.dot-flashing::before {
    left: -12px;
    animation: dotFlashing 1s infinite linear 0.25s;
}

.dot-flashing::after {
    left: 12px;
    animation: dotFlashing 1s infinite linear 0.5s;
}

/* 错误提示 */
.error-message {
    background: #fff3f3;
    border: 1px solid #ffd6d6;
    color: #ff4d4f;
    padding: 12px;
    border-radius: 8px;
    margin-top: 8px;
    display: flex;
    align-items: center;
    gap: 8px;
}

.error-message button {
    background: #ff4d4f;
    padding: 4px 12px;
    height: auto;
}

.error-message button:hover {
    background: #ff3336;
}

/* 滚动条样式 */
.messages-container::-webkit-scrollbar {
    width: 6px;
}

.messages-container::-webkit-scrollbar-track {
    background: rgba(0, 0, 0, 0.05);
}

.messages-container::-webkit-scrollbar-thumb {
    background: rgba(24, 144, 255, 0.3);
    border-radius: 3px;
}

/* 动画效果 */
@keyframes messageAppear {
    from {
        opacity: 0;
        transform: translateY(8px);
    }

    to {
        opacity: 1;
        transform: translateY(0);
    }
}

@keyframes dotFlashing {
    0% {
        opacity: 0.2;
        transform: scale(0.9);
    }

    50% {
        opacity: 1;
        transform: scale(1.1);
    }

    100% {
        opacity: 0.2;
        transform: scale(0.9);
    }
}
</style>